package cn.gson.crm.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户登录过滤器
 */

public class LoginFilter implements Filter {
	public static final String USER_SESSION_KEY = "emplo";
    /**
     * Default constructor. 
     */
    public LoginFilter() {
      
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		String path = request.getServletPath();
		// 登录请求和静态目录下面的请求不进行过滤
		if (session.getAttribute(USER_SESSION_KEY) == null && !"/login".equalsIgnoreCase(path) && !path.startsWith("/static/")) {
			// 判断是否是ajax请求
			if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
				response.sendError(401, "Not Login");
			} else {
				String basePath = (String) request.getAttribute(CommonFilter.BASE_PATH_ATTR_KEY);
				// 非ajax请求直接重定向到登录界面
				response.sendRedirect(basePath + "login");
			}
		} else if ("/".equals(path)) {
			response.sendRedirect("after/login");
		} else {
			chain.doFilter(req, resp);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	
	}

}
